<template>
  <!-- 获取表格数据 -->
  <div style="height: 100%">
    <el-row>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="查询时间">
          <el-date-picker
            v-model="queryForm.searchTime"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime"
          />
        </el-form-item>
        <el-form-item label="时间间隔">
          <el-select style="width: 100px" v-model="queryForm.interval" placeholder="选择时间间隔">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTableData">查询</el-button>
          <el-button type="primary" plain @click="showQx">查看曲线</el-button>
          <el-button type="primary" plain @click="exportData">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-table :data="tableData" style="height: calc(100% - 94px)" v-loading="loading" border>
      <el-table-column prop="ts" label="时间"></el-table-column>
      <el-table-column prop="v" label="值"></el-table-column>
      <el-table-column prop="operate" label="操作" align="center">
        <template #default="scope">
          <el-button @click="updateTagValue(scope.row)">修改</el-button>
        </template>
      </el-table-column>
      <!-- Add more columns as needed -->
    </el-table>
    <div style="float: right">
      <el-pagination
        style="margin-top: 12px"
        background
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        @current-change="handlePageChange"
      >
      </el-pagination>
    </div>
  </div>
  <el-dialog
    title="测点曲线"
    v-model="showQxVisiable"
    width="400px"
    style="height: 800px; width: 95%; margin-top: 40px"
  >
    <div ref="myChart" id="echartDiv" style="width: 100%; height: 100%"></div>
  </el-dialog>
  <el-dialog title="修改值" v-model="updateValueVisible" width="500px">
    <el-form :model="currentValueModel" label-width="auto">
      <el-form-item label="时间">
        <el-input v-model="currentValueModel.ts" disabled />
      </el-form-item>
      <el-form-item label="值">
        <el-input-number
          style="width: 100%"
          v-if="props.tableType == 'FLOAT' || props.tableType == 'DOUBLE'"
          v-model="currentValueModel.v"
        />
        <el-input-number
          v-else-if="props.tableType == 'INT'"
          style="width: 100%"
          :precision="0"
          :step="1"
          v-model="currentValueModel.v"
        />
        <el-select v-else v-model="currentValueModel.v" style="width: 100%">
          <el-option v-for="item in booleanOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateValueVisible = false">取消</el-button>
        <el-button type="primary" @click="updateTagValueConfirm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="tsx" setup>
import { ref, defineProps, onMounted, watch } from "vue";
import { queryHistoryData, updateTsValue } from "../../api";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import axios from 'axios'
import { defaultAxios } from '@/utils/http/index.js'
import * as echarts from 'echarts';
import { qxOption } from './qx2';

const loading = ref(false)

const showQxVisiable = ref(false);
const props = defineProps({
  dbName: {
    type: String,
    required: true,
  },
  tableName: {
    type: String,
    required: true,
  },
  tableType: {
    type: String,
    required: true,
  },
  dialogWidth: {
    type: Number,
    required: true,
  },
  height: {
    type: Number,
    required: true,
  },
  visiable: {
    type: Boolean,
    required: true,
  },
	dbInfo:{
		type:Object,
		default:{},
	},
	databaseInfo:{
		type:Array,
		default:[],
	}
});

/**
 * 选项
 */
const options = [
  {
    value: "0",
    label: "原始",
  },
  {
    value: "5",
    label: "5秒",
  },
  {
    value: "10",
    label: "10秒",
  },
  {
    value: "30",
    label: "30秒",
  },
  {
    value: "60",
    label: "1分钟",
  },
  {
    value: "300",
    label: "5分钟",
  },
];

//从0点开始
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const queryForm = ref({
  searchTime: [],
  interval: "0",
});

onMounted(() => {
  initQueryForm();
});

watch(
  () => props.visiable,
  (newval) => {
    if (newval) {
      pageSize.value = 500;
      currentPage.value = 1;
      getTableData();
    }
  }
);

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(500);
const currentPage = ref(1);
const store = {
	info:props.dbInfo,
	databaseInfo: props.databaseInfo,
};

const initQueryForm = () => {
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let startTime = year + "-" + month + "-" + day + " 00:00:00";
  let endTime = year + "-" + month + "-" + day + " 23:59:59";
  queryForm.value.searchTime = [startTime, endTime];
};
const showQx = async () => {
    showQxVisiable.value = true;
    let payload = {
      start: queryForm.value.searchTime[0],
      end: queryForm.value.searchTime[1],
      step: queryForm.value.interval,
      name: props.tableName,
      // pageNum: currentPage.value,
      // pageSize: pageSize.value,
      pageNum: 1,
      pageSize: 10000,
      dbConfig: {
        ...store.info,
        dbName: props.dbName,
      },
    };
    

  queryHistoryData(payload)
    .then((r) => {
      let list = r.data.list;
      //总数
      total.value = r.data.total;
      //页数
      // pageSize.value = total.value / pageSize.value + 1;
      var timeArr = [];
      var dataArr = [];
      if (list.length > 0) {
        tableData.value = list.map((item: any, index: number) => {
          // total.value = r.data.total;
          timeArr.unshift(moment(item.ts).format("YYYY-MM-DD HH:mm:ss"));
          dataArr.unshift([moment(item.ts).format("YYYY-MM-DD HH:mm:ss"),item.v]);
          return {
            ts: moment(item.ts).format("YYYY-MM-DD HH:mm:ss"),
            v: item.v,
          };
        });

        setTimeout(() => {
              // 基于准备好的dom，初始化echarts实例
              let myChart = echarts.init(document.getElementById("echartDiv"));
              // 绘制图表
              // console.log(qxOption);
              qxOption.title = {text: props.tableName};
              qxOption.legend = {
                data: [props.tableName],
              };
              qxOption.xAxis[0].data = timeArr;
              qxOption.series = [{
                name: props.tableName,
                type: "line",
                stack: "历史值",
                data: dataArr,
              }];
              myChart.setOption(qxOption);
        }, 500);
      } else {
        tableData.value = [];
        total.value = 0;
      }
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        message: err,
        type: "error",
      });
    });
};
//导出数据
const exportData = async () => {

  
  try {
    loading.value= true;
    let data = {
      start: queryForm.value.searchTime[0],
      end: queryForm.value.searchTime[1],
      step: queryForm.value.interval,
      name: props.tableName,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      dbConfig: {
        ...store.info,
        dbName: props.dbName,
      },
    };
    const response = await axios({
      url: defaultAxios.getBaseUrl()+'/rtdb/api/v1/exportData', // 后端API端点
      method: 'POST',
      data,
      responseType: 'blob', // 设置响应类型为二进制
    });
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'data.xlsx'; // 导出文件名
    link.click();
    loading.value= false;
  } catch (error) {
    console.error('导出失败:', error);
  }finally{
    loading.value= false;
  }

};
const getTableData = async () => {
  let payload = {
    start: queryForm.value.searchTime[0],
    end: queryForm.value.searchTime[1],
    step: queryForm.value.interval,
    name: props.tableName,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    dbConfig: {
      ...store.info,
      dbName: props.dbName,
    },
  };

  queryHistoryData(payload)
    .then((r) => {
      let list = r.data.list;
      //总数
      total.value = r.data.total;
      //页数
      // pageSize.value = total.value / pageSize.value + 1;
      if (list.length > 0) {
        tableData.value = list.map((item: any, index: number) => {
          total.value = r.data.total;
          return {
            ts: moment(item.ts).format("YYYY-MM-DD HH:mm:ss.SSS"),
            v: item.v,
          };
        });
      } else {
        tableData.value = [];
        total.value = 0;
      }
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        message: err,
        type: "error",
      });
    });
};

const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  getTableData();
};
const booleanOption = [
  { value: "true", label: "True" },
  { value: "false", label: "False" },
];
const currentValueModel = ref(null);
const updateValueVisible = ref(false);
const updateTagValue = (row) => {
  currentValueModel.value = JSON.parse(JSON.stringify(row));
  updateValueVisible.value = true;
};

const updateTagValueConfirm = () => {
  ElMessageBox.confirm("确认修改测点值?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let dbConfig = {
      ...store.info,
      dbName: props.dbName,
    };
    let tagInfo = {
      tagName: props.tableName,
    };
    let tagData = {
      ts: new Date(currentValueModel.value.ts).getTime(),
      v: currentValueModel.value.v,
    };
    let data = {
      dbConfig,
      tagInfo,
      tagData,
    };
    updateTsValue(data)
      .then((res) => {
        if (res.code == 200 && res.data) {
          getTableData();
        } else {
          ElMessage.error("更新值失败：" + res.msg);
        }
        updateValueVisible.value = false;
      })
      .catch((e) => {
        console.log(e);
        updateValueVisible.value = false;
      });
  });
};

// Fetch initial data
getTableData();
</script>
